package cn.lyl.user.service.impl;

import cn.lyl.basic.exception.BusinessException;
import cn.lyl.basic.util.Md5Utils;
import cn.lyl.basic.util.StrUtils;
import cn.lyl.user.domain.Logininfo;
import cn.lyl.user.domain.User;
import cn.lyl.user.mapper.LogininfoMapper;
import cn.lyl.user.mapper.UserMapper;
import cn.lyl.user.service.IUserService;
import cn.lyl.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 手机注册
     * @param map
     */

    @Override
    public void registerPhone(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //一、校验
        //1.空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) ||
            StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)){
            throw new BusinessException("信息不能为空");
        }
        //2.密码是否一致
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次密码不一致");
        }
        //3.手机验证码是过期，是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            throw new BusinessException("手机验证码已经过期！");
        }
        //redis中手机验证码的储存格式【业务键：手机号 - 手机验证码：时间戳】
        if(!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误！");
        }
        //二、添加数据库
        //将一个对象转换为另一个对象的时候，而且代码量多得时候就用obj2obj
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.add(logininfo);
        //2.添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }



    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则：
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户手机号码注册
        logininfo.setDisable(true);//手机注册默认启用
        return logininfo;
    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        user.setUsername(map.get("phone"));
        user.setPhone(map.get("phone"));
        //生成32随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }


    /**
     * 邮箱注册
     * @param map
     */
    @Override
    public void registerEmail(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");

        //一、校验
        //1.空值
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空");
        }
        //2.密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //3.当前邮箱是否注册过
        User userEmail = userMapper.findByEmail(email);
        if(userEmail!=null){
            throw new BusinessException("当前邮箱已注册，请直接登录，忘记密码请联系管理员！");
        }
        //邮箱格式是否正确
        String format = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$";
        if (!email.matches(format)){
            throw new BusinessException("邮箱格式有误！");
        }

        //二、添加数据库
        //将一个对象转换为另一个对象的时候，而且代码量多得时候就用obj2obj
        User user = emailMap2User(map);
        Logininfo logininfo = emailUser2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.add(logininfo);
        //2.添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

        //发送邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("1501828087@qq.com");//平台的邮箱
        helper.setSubject("邮箱账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>恭喜你,账号注册成功，赶快激活吧！</h1>" +
                "<a href='http://172.16.36.225:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",true);
        helper.setTo(email);
        javaMailSender.send(mimeMessage);
    }

    /**
     * 激活邮件
     * @param id
     */
    @Override
    public void active(Long id) {
        userMapper.updateState(1,id);
    }

    private Logininfo emailUser2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则：
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户邮箱注册
        return logininfo;
    }

    private User emailMap2User(Map<String, String> map) {
        User user = new User();
        //先获取前端传入的邮箱
        String email = map.get("email");
        //在添加到user中
        user.setUsername(email);
        user.setEmail(email);
        //生成32随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String pwdMd5 = Md5Utils.encrypByMd5(map.get("password") + salt);
        user.setSalt(salt);
        user.setPassword(pwdMd5);
        user.setState(0);
        return user;
    }

    //模块重构
    @Override
    @Transactional
    public void add(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        //获取到自增id
        logininfoMapper.add(logininfo);

        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    @Override
    @Transactional
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.findOne(id);

        //删除user
        super.del(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());
    }

    @Override
    @Transactional
    public void update(User user) {//前端传过来的user是没有登陆信息id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //loginfo_id
        User oldUser = userMapper.findOne(user.getId());

        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.findOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置回以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

}
